<?php
class JobsController extends AppController {

	var $name = 'Jobs';
	var $helpers = array('Html', 'Form');
    
    function get_count()
    {
        $count = $this->Job->find('count',array('conditions'=>array('Job.status'=>1)));
        return $count;
    }
    
    function by_category()
    {
        $query = "SELECT fields.id,fields.name,(SELECT count(*) FROM `fields_jobs`,`jobs` WHERE fields_jobs.field_id = fields.id AND fields_jobs.job_id = jobs.id AND jobs.status = 1  AND end_date >= '".date("Y-m-d")."') total FROM `fields`";
        return $this->Job->query($query);   
    }
    
    function by_city()
    {
        $query = "SELECT cities.id,cities.name,(SELECT count(*) FROM `jobs` WHERE jobs.city_id = cities.id AND jobs.status=1  AND end_date >= '".date("Y-m-d")."') total FROM `cities` ORDER BY cities.name";
        return $this->Job->query($query);  
    }

    function by_career()
    {
        $temp['entry'] = $this->Job->query("SELECT count(*) as total FROM `jobs` WHERE entry=1 AND status=1 AND end_date >= '".date("Y-m-d")."'");    
        $temp['middle'] = $this->Job->query("SELECT count(*) as total FROM `jobs` WHERE middle=1 AND status=1 AND end_date >= '".date("Y-m-d")."'");    
        $temp['senior'] = $this->Job->query("SELECT count(*) as total FROM `jobs` WHERE senior=1 AND status=1 AND end_date >= '".date("Y-m-d")."'");    
        $temp['top'] = $this->Job->query("SELECT count(*) as total FROM `jobs` WHERE top=1 AND status=1 AND end_date >= '".date("Y-m-d")."'");  
        return $temp;  
    }
    
    function search()
    {
        $this->set('choose1',2);
        $this->Job->Field->recursive=-1;
        $fields = $this->Job->Field->find('all',array('order'=>'Field.name'));

        $this->Job->City->recursive=-1;
        $cities = $this->Job->City->find('all',array('order'=>'City.name'));

        $this->Job->Academic->recursive=-1;
        $academics = $this->Job->Academic->find('all');

        $this->set(compact('fields', 'cities', 'academics'));             
    }
    
    function search_result( $id = null )
    {
        
        $this->set('choose1',2);
        if(!empty($this->passedArgs['by']))
        {
            /*
            if(!$this->passedArgs['page'])
            {  $this->passedArgs['page']=1; }                                                
            
            $from = ($this->passedArgs['page']-1) * $record;
            */
            if(!empty($this->passedArgs['tid']) && $this->passedArgs['by']!='all' )
            {
                $query = "SELECT jobs.id FROM `jobs` ";
                
                if($this->passedArgs['by']=='category')
                { $query .=", `fields_jobs` WHERE fields_jobs.job_id=jobs.id AND fields_jobs.field_id = ".$this->passedArgs['tid']; }
                
                if($this->passedArgs['by']=='location')
                { $query .="WHERE jobs.city_id=".$this->passedArgs['tid']; }
                
                if($this->passedArgs['by']=='career')
                {
                    if( $this->passedArgs['tid'] == 'entry' )
                    { $query.="WHERE jobs.entry=1"; }
                    if( $this->passedArgs['tid'] == 'middle' )
                    { $query.="WHERE jobs.middle=1"; }
                    if( $this->passedArgs['tid'] == 'senior' )
                    { $query.="WHERE jobs.senior=1"; }
                    if( $this->passedArgs['tid'] == 'top' )
                    { $query.="WHERE jobs.top=1"; }
                }
                
            }
            else
            { $this->set('invalid',true); }
            
            if( $this->passedArgs['by']=='all' )
            { $query = "SELECT jobs.id FROM `jobs`"; }
            
            
        }
        else
        { $this->set('invalid',true); }
        
        
        if(!empty($_POST['bykeyword']))
        {
            /*
            if($_POST['field']==0)
            {
                $query = "SELECT jobs.id FROM `jobs` ";
                if($_POST['category']==0)
                { $query.="WHERE position LIKE '%".$_POST['keyword']."%'"; }
                if($_POST['category']==1)
                { $query.=", `employers` WHERE employers.id = jobs.employer_id AND employers.company_name LIKE '%".$_POST['keyword']."%'"; }
                if($_POST['category']==2)
                { $query.="WHERE ( criteria LIKE '%".$_POST['keyword']."%' OR jobdesc LIKE '%".$_POST['keyword']."%' OR `desc` LIKE '%".$_POST['keyword']."%' ) "; }
            }
            else
            {*/
			$query = "SELECT jobs.id FROM `jobs`,`fields_jobs` ";
			if($_POST['category']==0)
			{ $query.="WHERE jobs.position LIKE '%".$_POST['keyword']."%'"; }
			if($_POST['category']==1)
			{ $query.=", `employers` WHERE employers.id = jobs.employer_id AND employers.company_name LIKE '%".$_POST['keyword']."%'"; }
			if($_POST['category']==2)
			{ $query.="WHERE ( jobs.criteria LIKE '%".$_POST['keyword']."%' OR jobs.jobdesc LIKE '%".$_POST['keyword']."%' OR jobs.`desc` LIKE '%".$_POST['keyword']."%' )"; }
			
			if($_POST['field']!=0)
			{ $query .=" AND fields_jobs.job_id = jobs.id AND fields_jobs.field_id = ".$_POST['field']; }
            //}
            
        }        

        if(!empty($_POST['bykeyword2']))
        {
            $query = "SELECT jobs.id FROM `jobs`,`employers` WHERE employers.id = jobs.employer_id AND (";
            
            if($_POST['match']==1)
            { $word = 'AND'; }
            else
            { $word = 'OR'; }
            
            $keywords = explode(",",$_POST['keyword']);
            
                $i=0;
                foreach($keywords as $keyword)
                {
                    if($i)
                    { $query .= $word; }
                    if($_POST['search']==0)
                    $query.=" jobs.position LIKE '%".$keyword."%' ";
                    if($_POST['search']==1) 
                    $query.=" employers.company_name LIKE '%".$keyword."%' ";
                    if($_POST['search']==2) 
                    $query.=" ( jobs.criteria LIKE '%".$keyword."%' OR jobs.jobdesc LIKE '%".$keyword."%' OR jobs.desc LIKE '%".$keyword."%' ) ";
                    $i=1;
                }
                $query .=" ) ";
                                         
        }   
        
        if(!empty($_POST['byall']))
        {
            $query = "SELECT jobs.id FROM `jobs`,`fields_jobs`,`employers` WHERE employers.id = jobs.employer_id AND fields_jobs.job_id = jobs.id ";
            
            if ($_POST['keyword']!='')
            {
                if($_POST['match']==1)
                { $word = 'AND'; }
                else
                { $word = 'OR'; }
                
                $keywords = explode(",",$_POST['keyword']);
                
                $query .=" AND (";
                    $i=0;
                    foreach($keywords as $keyword)
                    {
                        if($i)
                        { $query .= $word; }
                        if($_POST['search']==0)
                        $query.=" jobs.position LIKE '%".$keyword."%' ";
                        if($_POST['search']==1) 
                        $query.=" employers.company_name LIKE '%".$keyword."%' ";
                        if($_POST['search']==2) 
                        $query.=" ( jobs.criteria LIKE '%".$keyword."%' OR jobs.jobdesc LIKE '%".$keyword."%' OR jobs.desc LIKE '%".$keyword."%' ) ";
                        $i=1;
                    }
                    $query .=" ) ";
            }
            
            
            if($_POST['city']!=0)
            { $query .= " AND jobs.city_id = ".$_POST['city']; }         

            if($_POST['field']!=0)
            { $query .= " AND fields_jobs.field_id = ".$_POST['field']; }         

            if( @$_POST['entry'] || @$_POST['middle'] || @$_POST['senior'] || @$_POST['top'] )
            {
                $query .= " AND ( ";
                if(!empty($_POST['entry']))
                {  $query .= " jobs.entry = 1 "; $query .=" OR "; }
                if(!empty($_POST['middle']) )
                {  $query .= " jobs.middle = 1 "; $query .=" OR "; }
                if(!empty($_POST['senior']))
                {  $query .= " jobs.senior = 1 "; $query .=" OR "; }
                if(!empty($_POST['top']))
                {  $query .= " jobs.top = 1 "; $query .=" OR "; }
                $query=substr($query,0,strlen($query)-3);
                $query .= " ) ";            
            }
            
            if($_POST['academic']!=0)
            {   
                if($_POST['academic1']==0)
                { $query .= " AND jobs.academic_id = ".$_POST['academic']; }
                if($_POST['academic1']==1)
                { $query .= " AND jobs.academic_id >= ".$_POST['academic']; }
                if($_POST['academic1']==2)
                { $query .= " AND jobs.academic_id <= ".$_POST['academic']; }                                
            }
            
            if($_POST['exp']!='')
            {   
                if($_POST['exp1']==0)
                { $query .= " AND jobs.experience = ".$_POST['exp']; }
                if($_POST['exp1']==1)
                { $query .= " AND jobs.experience >= ".$_POST['exp']; }
                if($_POST['exp1']==2)
                { $query .= " AND jobs.experience <= ".$_POST['exp']; }                                
            }
            
            if( @$_POST['parttime'] || @$_POST['fulltime'] || @$_POST['freelance'] || @$_POST['contract'] || @$_POST['temporary'] )
            {
                $query .= " AND ( ";
                if(!empty($_POST['parttime']) )
                {  $query .= " jobs.parttime = 1 "; $query .=" OR "; }            
                if(!empty($_POST['fulltime']) )
                {  $query .= " jobs.fulltime = 1 "; $query .=" OR "; }            
                if(!empty($_POST['freelance']) )
                {  $query .= " jobs.freelance = 1 "; $query .=" OR "; }            
                if(!empty($_POST['contract']) )
                {  $query .= " jobs.contract = 1 "; $query .=" OR "; }            
                if(!empty($_POST['temporary']) )
                {  $query .= " jobs.temporary = 1 "; $query .=" OR "; }            
                $query=substr($query,0,strlen($query)-3);
                $query .= " ) ";
            }
            
            if($_POST['salary']!=0)
            {
                if(!empty($_POST['salary1']) )
                { $query .= " AND ( jobs.salary = ".$_POST['salary']." OR jobs.salary=0 )"; }
                else
                { $query .= " AND jobs.salary = ".$_POST['salary']; }
            }
            
        }     
        if(@$query)
        {
            $query2="SELECT cities.name, jobs.id, jobs.position, jobs.created, jobs.salary, jobs.experience, jobs.entry, jobs.middle, jobs.senior, jobs.top, employers.id ,employers.company_name FROM `jobs`,`employers`,`cities` WHERE jobs.employer_id = employers.id AND cities.id = jobs.city_id AND jobs.id IN (".$query.") ";
            $query2 .=" AND jobs.status = 1  AND end_date >= '".date("Y-m-d")."' ORDER BY jobs.created DESC,jobs.id DESC";
            $data = $this->Job->query($query2);
            $this->set('jobs',$data);
            
        }
        else
        {
            $this->Session->setFlash(__('Please start a new search', true));
            $this->redirect(array('controller'=>'jobs', 'action'=>'search'),null, true);
        }    
    }
    function post()
    {
        if($this->Session->read('User.type')=='employer')
        {
            $this->set('choose1',42);
            
            $this->Job->recursive=-1;
            if(!empty($this->data))
            {
                $this->data['Job']['desc'] = str_replace("'","`",$this->data['Job']['desc']);
                $this->data['Job']['jobdesc'] = str_replace("'","`",$this->data['Job']['jobdesc']);
                $this->data['Job']['criteria'] = str_replace("'","`",$this->data['Job']['criteria']);
                $this->data['Job']['note'] = str_replace("'","`",$this->data['Job']['note']);
                
                $this->data['Job']['employer_id']=$this->Session->read('User.id');         
                $this->Job->create();
                $this->Job->save($this->data);
                $this->Session->setFlash(__('Your Job successfully created', true));
                $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true);
            }
            
            $fields		= $this->Job->Field->find('list',array('order'=>'Field.name'));
            $templates	= $this->Job->Template->find('list');
            $cities		= $this->Job->City->find('list',array('order'=>'City.name'));
            $academics	= $this->Job->Academic->find('list');
			$skills		= $this->Job->Skill->find('list');
            $this->set(compact('fields', 'templates', 'cities', 'academics','skills'));        
        }
        else
        { 
            $this->Session->setFlash(__('Please login first', true));
            $this->redirect(array('controller'=>'employers', 'action'=>'login'),null, true);        
        }
    
    }
    
    function edit($id = null) 
    {
        if($this->Session->read('User.type')=='employer')
        {
            $this->set('choose1',42);
            if(!empty($this->data))
            {
                if($this->data['Field'])
                {
                    $query = "DELETE FROM `fields_jobs` WHERE job_id = ".$this->data['Job']['id'];
                    $this->Job->query($query);                
                    foreach($this->data['Field']['Field'] as $temp)
                    {
                        $query = "INSERT INTO `fields_jobs` (field_id,job_id) VALUES (".$temp.",".$this->data['Job']['id'].")";
                        $this->Job->query($query);
                    }
                }
                
                $this->data['Job']['desc'] = str_replace("'","`",$this->data['Job']['desc']);
                $this->data['Job']['jobdesc'] = str_replace("'","`",$this->data['Job']['jobdesc']);
                $this->data['Job']['criteria'] = str_replace("'","`",$this->data['Job']['criteria']);
                $this->data['Job']['note'] = str_replace("'","`",$this->data['Job']['note']);
                                
                $this->Job->save($this->data['Job']);
                $this->Session->setFlash(__('Your Job successfully edited', true));
                $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true);               
            }

            
            if(empty($this->data))
            {
                $this->Job->recursive=1;
                $data = $this->Job->find('first',array('conditions'=>array('Job.id'=>$id, 'Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>0 ) ));
                if(empty($data))
                {
                    $this->Session->setFlash(__('Invalid Link', true)); 
                    $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true);
                }
                else
                {
                    $this->set('choose1',42);
                    $this->data = $this->Job->read(null,$id);
                }
                
            }
                    
            $fields = $this->Job->Field->find('list',array('order'=>'Field.name'));
            $templates = $this->Job->Template->find('list');
            $cities = $this->Job->City->find('list',array('order'=>'City.name'));
            $academics = $this->Job->Academic->find('list');
            $this->set(compact('fields', 'templates', 'cities', 'academics'));          
        }
        else
        { 
            $this->Session->setFlash(__('Please login first', true));
            $this->redirect(array('controller'=>'employers', 'action'=>'login'),null, true);        
        }
    }    
    
    function payment($id = null)
    {
        $this->set('choose1',42);
        if(!empty($this->data))
        {
            if($this->data['Job']['slip']['type']=='image/gif' || $this->data['Job']['slip']['type']=='image/jpeg' || $this->data['Job']['slip']['type']=='image/pjpeg' || $this->data['Job']['slip']['type']=='image/png')
            {

                $this->Job->recursive=-1;                    
                $data = $this->Job->read(null,$this->data['Job']['id']);
                if( file_exists($data['Job']['slip']) && $data['Job']['slip']!='' && $data['Job']['slip']!='n/a' )
                {
                    unlink($data['Job']['slip']);
                }

                
                $name = substr($this->data['Job']['slip']['name'],0,strpos($this->data['Job']['slip']['name'],'.'));
                $type = substr($this->data['Job']['slip']['name'],strpos($this->data['Job']['slip']['name'],'.'),5); 
                $destination = JOB_SLIP_DIRECTORY.$this->data['Job']['id'].$type;
                if( move_uploaded_file($this->data['Job']['slip']['tmp_name'],$destination)  )
                {
                    $this->data['Job']['slip']=$destination;
                    $this->Job->save($this->data); 
                    $this->Session->setFlash(__('Thank you for your payment', true));
                    $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true); 
                }
                else
                { $this->Session->setFlash(__('Upload failed, please try again', true)); }
            }
            else
            { $this->Session->setFlash(__('Please provide image file', true)); }     
            $this->Job->recursive=-1;
            $this->data = $this->Job->find('first',array(  'conditions'=>array('Job.id'=>$id,'Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>0   )));
        }
        else
        {
            if($this->Session->read('User.type')=='employer')
            {
                $this->Job->recursive=-1;
                $this->data = $this->Job->find('first',array(  'conditions'=>array('Job.id'=>$id,'Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>0   )));
                if(empty($this->data))
                { 
                    $this->Session->setFlash(__('Invalid ID', true));
                    $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true);
                }
            }
            else
            {
                $this->Session->setFlash(__('Please login first', true));
                $this->redirect(array('controller'=>'employers', 'action'=>'login'),null, true);
            }
        }        
    }    

    function view($id = null) 
    {
        if($id)
        {
            $this->Job->recursive=1;
            $data = $this->Job->read(null,$id);
            if(!empty($data)) 
            {
                if($data['Job']['status']==0)
                {
                    $this->layout = 'job';
                    if( ($this->Session->read('User.type')=='employer' && $data['Job']['employer_id']==$this->Session->read('User.id')) || $this->Session->read('User.type')=='admin' )
                    {
                        $this->set('visitor','owner');
                        $this->set('data',$data);
                    }
                    else
                    { 
                        $this->Session->setFlash(__('Invalid ID for jobs', true));
                        $this->redirect(array('controller'=>'jobs', 'action'=>'index'),null, true);
                    }
                }
                else
                {
                    $this->layout = 'job';
                    if( $this->Session->read('User.type')=='employer' && $data['Job']['employer_id']==$this->Session->read('User.id') )
                    {
                        $this->set('visitor','owner');
                        $this->set('data',$data);
                    }
                    else
                    {
                        $this->set('visitor','quest');
                        $this->set('data',$data);
                    }
                }
				$this->set('id',$id);
            }
            else
            { 
                $this->Session->setFlash(__('Invalid ID for jobs', true));
                $this->redirect(array('controller'=>'jobs', 'action'=>'index'),null, true);
            }                          
        }
        else
        { 
            $this->Session->setFlash(__('Invalid ID for jobs', true));
            $this->redirect(array('controller'=>'jobs', 'action'=>'index'),null, true);
        }
    }

    function my_jobs()
    {
        if($this->Session->read('User.type')=='employer')
        {
            $this->set('choose1',42);
            $this->Job->recursive=-1;            
            $all = $this->Job->find('all',array('conditions'=>array('Job.employer_id'=>$this->Session->read('User.id')),'order'=>'Job.created DESC'));
            $end = $this->Job->find('all',array('conditions'=>array('Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>1,'Job.end_date < '=>date("Y-m-d")),'order'=>'Job.created DESC'));
            $post = $this->Job->find('all',array('conditions'=>array('Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>1,'Job.end_date >= '=>date("Y-m-d")),'order'=>'Job.created DESC'));
            $wait = $this->Job->find('all',array('conditions'=>array('Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>0),'order'=>'Job.created DESC'));
            
            
            $this->set('all',$all);        
            $this->set('end',$end);        
            $this->set('post',$post);        
            $this->set('wait',$wait);        
        }
        else
        { 
            $this->Session->setFlash(__('Please login first', true));
            $this->redirect(array('controller'=>'employers', 'action'=>'login'),null, true); 
        }    
    }
    
    function close($id = null)
    {
        if($this->Session->read('User.type')=='employer')
        {
            $this->Job->recursive=-1;
            $data = $this->Job->find('all',array('conditions'=>array('Job.id'=>$id, 'Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>1 ) ));
            if(empty($data))
            {
                $this->Session->setFlash(__('Invalid Link', true)); 
                $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true);
            }
            else
            {                                                                                    
                $temp['Job']['id']=$id;
                $yesterday = mktime(0 , 0, 0, date("m"), date("d")-1, date("Y") );
                $temp['Job']['end_date']= date("Y-m-d", $yesterday);
                $this->Job->save($temp);
                $this->Session->setFlash(__('Your Job has been closed', true)); 
                $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true);
            }
        }
        else
        { 
            $this->Session->setFlash(__('Please login first', true));
            $this->redirect(array('controller'=>'employers', 'action'=>'login'),null, true);        
        }    
    }
    
    function resumes_alert()
    {
        if($this->Session->read('User.type')=='employer')
        {
            $this->set('choose1',44);
            $this->Job->recursive=-1;            
            $data = $this->Job->find('all',array('conditions'=>array('Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>1),'order'=>'Job.created'));
            
            $this->set('jobs',$data);        
        }
        else
        { 
            $this->Session->setFlash(__('Please login first', true));
            $this->redirect(array('controller'=>'employers', 'action'=>'login'),null, true); 
        }    
    }    
    
	function index($id = null) 
    {

        $count = EMPLOYER_PER_PAGE;
        $this->set('choose1',1);
        $query = "SELECT employers.id, employers.company_name, employers.logo, (SELECT count(*) FROM `jobs` WHERE jobs.employer_id = employers.id AND jobs.status=1) as jumlah FROM `employers` WHERE employers.status=1 AND employers.logo <> '' ORDER BY jumlah DESC LIMIT 0,".$count;
        $employers = $this->Job->query($query);
        $this->set('top_employers',$employers);
        
        $query = "SELECT advs.id, advs.image FROM `advs` WHERE advs.status=1 AND advs.end_date >= ".date("Y-m-d");
        $advs = $this->Job->query($query);
        $this->set('advs',$advs);

        //$count = $this->Job->find('count',array('conditions'=>array('Job.status'=>1)));
        $query = "SELECT count(*) as jumlah FROM `jobs` WHERE status=1 AND end_date >= '".date("Y-m-d")."'";
        $count = $this->Job->query($query);
        $this->set('count_job',$count[0][0]['jumlah']); 
        
//        $count = $this->Job->find('count',array('conditions'=>array('Job.status'=>1,'Job.end_date' >= date("Y-m-d"))));
//        $this->set('count_job',$count);
        
        $query = "SELECT count(*) as jumlah FROM `jobseekers` WHERE status=1";
        $count = $this->Job->query($query);
        $this->set('count_jobseeker',$count[0][0]['jumlah']);
        
        $query = "SELECT count(*) as jumlah FROM `employers` WHERE status=1";
        $count = $this->Job->query($query);
        $this->set('count_employer',$count[0][0]['jumlah']);

        
        if($id !=null )
        { $this->redirect(array('action'=>'index')); }
	}

    function login_admin() 
    {
        $this->layout='admin';
        $admin_name = 'admin';
        $admin_pass = 'admin';
        if(!empty($this->data))
        { 
            if($this->data['Job']['username']==$admin_name && $this->data['Job']['password']==$admin_pass)
            {
                $temp['type']= 'admin';
                $this->Session->write('User',$temp);
                $this->redirect(array('controller'=>'jobs', 'action'=>'menu_admin'),null, true);            
            }
        }
    }
    
    function menu_admin()
    {
        if($this->Session->read('User.type')=='admin')
        {
            $this->layout='admin';
        }
        else
        {
            $this->Session->setFlash('You are forbidden for this page');
            $this->redirect(array('controller'=>'jobs', 'action'=>'login_admin'),null, true);
        }    
    }
    
    function logout_admin()
    {
        $this->Session->del('User');
        $this->redirect(array('controller'=>'jobs', 'action'=>'login_admin')); 
    }    
    
    
    function index_admin()  
    {
        if($this->Session->read('User.type')=='admin')
        {
            $this->layout='ajax';
        }
        else
        {
            $this->Session->setFlash('You are forbidden for this page');
            $this->redirect(array('controller'=>'jobs', 'action'=>'login_admin'),null, true);
        }             
    }

    function filter_admin()  
    {
        $this->layout='ajax';
        if(!empty($this->data['category']))
        {
            $this->Job->recursive=0;
            $query = "SELECT jobs.*, cities.name ,employers.company_name FROM `jobs`,`employers`,`cities` WHERE jobs.city_id = cities.id AND employers.id = jobs.employer_id ";
                                                                 
            if($this->data['category']==2)
            { $query.= " AND jobs.status = 0 AND jobs.slip <> ''"; }
            if($this->data['category']==3)
            { $query.= " AND jobs.status = 1 AND jobs.end_date >= '".date("Y-m-d")."'"; }
            if($this->data['category']==4)
            { $query.= " AND jobs.status = 1 AND jobs.end_date < '".date("Y-m-d")."'"; }
            $mydate = date("Y-m-d", mktime(0, 0, 0, date('m')-6, date('d'), date('Y')));
            if($this->data['category']==5)
            { $query.= " AND jobs.status = 1 AND jobs.end_date < '".$mydate."'"; }
            if($this->data['category']==6)
            { $query.= " AND jobs.status = 0 AND jobs.slip = '' "; }
            if($this->data['category']==7)
            { $query.= " AND jobs.status = 0 AND jobs.slip = ''  AND advs.created < '".$mydate."'"; }

            if($this->data['id']!='')
            { $query.= " AND jobs.id=".$this->data['id']; }
            if($this->data['employer_id']!='')
            { $query.= " AND jobs.employer_id=".$this->data['employer_id']; }
            if($this->data['name']!='')
            { $query.= " AND jobs.position LIKE '%".$this->data['name']."%'"; }

            
            $jobs = $this->Job->query($query);
            $this->set('jobs',$jobs);
        }
        
        if(empty($this->data))
        {
            $query = "SELECT jobs.*, cities.name ,employers.company_name FROM `jobs`,`employers`,`cities` WHERE jobs.city_id = cities.id AND employers.id = jobs.employer_id ";
            $jobs = $this->Job->query($query);
            $this->set('jobs',$jobs);
        }
    }

    function slip_admin( $id = null )
    { 
        $this->layout = 'ajax';
        $this->Job->recursive=-1;        
        $data = $this->Job->read(null,$id);
        $this->set('data',$data);   
    }
    
    function approve_admin( $id = null )
    { 
        $data = $this->Job->query("SELECT * FROM jobs WHERE id = ".$id);
        $salary = $data[0]['jobs']['salary'];
        
        if( $salary == 0 )
        {        
            $query = "
            SELECT assistants.id FROM `assistants`,`assistants_fields`,`assistants_cities`,`jobs`,`fields_jobs`

            WHERE assistants_fields.assistant_id = assistants.id AND assistants_cities.assistant_id = assistants.id AND assistants.status <> 0 AND assistants.email=1 AND fields_jobs.job_id = jobs.id AND jobs.id = ".$id."

            AND assistants.academic_id >= jobs.academic_id 
            AND assistants_fields.field_id = fields_jobs.field_id 
            AND assistants_cities.city_id = jobs.city_id 

            AND assistants.experience >= jobs.experience
            AND assistants.negotiable <> 0
            AND ( assistants.negotiable = 1 OR jobs.salary = 0 )

            AND ( (assistants.parttime = 1 AND jobs.parttime=1) OR (assistants.fulltime = 1 AND jobs.fulltime=1) OR (assistants.freelance = 1 AND jobs.freelance=1) OR (assistants.contract = 1 AND jobs.contract=1) OR (assistants.temporary = 1 AND jobs.temporary=1) )
            AND ( (assistants.entry = 1 AND jobs.entry=1) OR (assistants.middle = 1 AND jobs.middle=1) OR (assistants.senior = 1 AND jobs.senior=1) OR (assistants.top = 1 AND jobs.top=1) )
            "; 
        }
        else
        {
            if($salary==1)
            { $temp = MIN_SALARY_1; $temp2=MAX_SALARY_1; }
            if($salary==2)
            { $temp = MIN_SALARY_2; $temp2=MAX_SALARY_2; }
            if($salary==3)
            { $temp = MIN_SALARY_3; $temp2=MAX_SALARY_3; }
            if($salary==4)
            { $temp = MIN_SALARY_4; $temp2=MAX_SALARY_4; }
            
            $query = "
            SELECT assistants.id FROM `assistants`,`assistants_fields`,`assistants_cities`,`jobs`,`fields_jobs`

            WHERE assistants_fields.assistant_id = assistants.id AND assistants_cities.assistant_id = assistants.id AND assistants.status <> 0 AND assistants.email=1 AND fields_jobs.job_id = jobs.id AND jobs.id = ".$id."

            AND assistants.academic_id >= jobs.academic_id 
            AND assistants_fields.field_id = fields_jobs.field_id 
            AND assistants_cities.city_id = jobs.city_id 

            AND assistants.experience >= jobs.experience
            AND ( assistants.salary <= ".$temp2.")

            AND ( ( (assistants.parttime = 1 AND jobs.parttime=1) OR (assistants.fulltime = 1 AND jobs.fulltime=1) OR (assistants.freelance = 1 AND jobs.freelance=1) OR (assistants.contract = 1 AND jobs.contract=1) OR (assistants.temporary = 1 AND jobs.temporary=1) ) OR (assistants.temporary=0 AND assistants.parttime=0 AND assistants.fulltime=0 AND assistants.contract=0 AND assistants.freelance=0) )
            AND ( ( (assistants.entry = 1 AND jobs.entry=1) OR (assistants.middle = 1 AND jobs.middle=1) OR (assistants.senior = 1 AND jobs.senior=1) OR (assistants.top = 1 AND jobs.top=1) ) OR (assistants.entry=0 AND assistants.middle=0 AND assistants.senior=0 AND assistants.top=0 ) )
            "; 
        }        
                
        
        $query2 = "SELECT email FROM `jobseekers` WHERE id IN (".$query.") AND status=1";  
        $email = $this->Job->query($query2);
        if(count($email))
        {
            foreach($email as $temp)
            {
                $to = $temp['jobseekers']['email'];
                $subject = "Job Alert - ".$data[0]['jobs']['position'];
                $setting = "Content-Type: text/html;". "\r\n";
                $setting = "From: admin@ITJobz.com ". "\r\n";
                $link = "<a href='http://www.itjobz.jux.in/jobs/view/".$id."'>".$data[0]['jobs']['position']."</a>";
                $body =    " Job Alert from ITJobz.com <br>".$link;                         
                @mail($to, $subject, $body, $setting);   
            }
        
        }

        $mydate = date("Y-m-d", mktime(0, 0, 0, date('m')+1, date('d'), date('Y')));
        $this->data['Job']['id']=$id;
        $this->data['Job']['status']=1;
        $this->data['Job']['created']=date("Y-m-d");
        $this->data['Job']['end_date']=$mydate;
        $this->Job->save($this->data);
        $this->redirect(array('controller'=>'jobs','action'=>'filter_admin'));


    }
    
    function edit_admin( $id = null )
    {
        if(!empty($this->data))
        {
            $this->Job->save($this->data);
            $this->redirect(array('controller'=>'jobs','action'=>'filter_admin'));    
        }
        else
        {
            $this->layout = 'ajax';
            $this->Job->recursive=-1;
            $this->data = $this->Job->read(null,$id);
        }
    }
    
    function delete_admin($id)
    {  
        if($this->Session->read('User.type')=='admin')
        {
            $this->layout = 'ajax';
            $this->Job->del($id);
            $this->redirect(array('controller'=>'jobs','action'=>'filter_admin'));
        }        
    }     
     
    function web_statistic()
    {
        if($this->Session->read('User.type')=='admin')
        {
            $this->layout='ajax';
        }
        else
        {
            $this->Session->setFlash('You are forbidden for this page');
            $this->redirect(array('controller'=>'jobs', 'action'=>'login_admin'),null, true);
        }     
    }
    
    function web_filter()
    {
        $this->layout='ajax';
        
        if( $this->data['period'] == 2 )
        { $mydate = date("Y-m-d", mktime(0, 0, 0, date('m'), date('d')-1, date('Y'))); }
        if( $this->data['period'] == 3 )
        { $mydate = date("Y-m-d", mktime(0, 0, 0, date('m'), date('d')-7, date('Y'))); }
        if( $this->data['period'] == 4 )
        { $mydate = date("Y-m-d", mktime(0, 0, 0, date('m')-1, date('d'), date('Y'))); }
        if( $this->data['period'] == 5 )
        { $mydate = date("Y-m-d", mktime(0, 0, 0, date('m')-6, date('d')-7, date('Y'))); }
        if( $this->data['period'] == 6 )
        { $mydate = date("Y-m-d", mktime(0, 0, 0, date('m'), date('d')-7, date('Y')-1)); }

        
        $jobseeker = "SELECT * FROM `jobseekers` WHERE status=1 ";
        $employer = "SELECT * FROM `employers` WHERE status=1 ";
        $job = "SELECT * FROM `jobs` WHERE status=1 ";
        $adv = "SELECT * FROM `advs` WHERE status=1 ";

        if($this->data['period']!=1)
        {
            $jobseeker.=" AND created >= '".$mydate."'";
            $employer.=" AND created >= '".$mydate."'";
            $job.=" AND created >= '".$mydate."'";
            $adv.=" AND created >= '".$mydate."'";
        }

        if($this->data['category']==1)
        {
            $jobseekers = $this->Job->query($jobseeker);
            $employers = $this->Job->query($employer);
            $jobs = $this->Job->query($job);
            $advs = $this->Job->query($adv);
        }
        if($this->data['category']==2)
        {
            $jobseekers = $this->Job->query($jobseeker);
            $employers = $this->Job->query($employer);
            $jobs = null;
            $advs = null;
        }        
        if($this->data['category']==3)
        {
            $jobseekers = null;
            $employers = null;
            $jobs = $this->Job->query($job);
            $advs = $this->Job->query($adv);
        }         
        if($this->data['category']==4)
        {
            $jobseekers = null;
            $employers = $this->Job->query($employer);
            $jobs = $this->Job->query($job);
            $advs = $this->Job->query($adv);
        } 
        
        $this->set('category',$this->data['category']);
        $this->set('period',$this->data['period']);
        $this->set('jobseekers',$jobseekers);
        $this->set('employers',$employers);
        $this->set('jobs',$jobs);
        $this->set('advs',$advs);
    }
    
    function detail($id)
    {
        $this->layout = 'ajax';
        $data = $this->Job->read(null,$id);
        $this->set('data',$data);        
    }
   
    function delete($id = null) 
    {
        if($this->Session->read('User.type')=='employer')
        {
            $this->Job->recursive=-1;
            $data = $this->Job->find('all',array('conditions'=>array('Job.id'=>$id, 'Job.employer_id'=>$this->Session->read('User.id'),'Job.status'=>0 ) ));
            if(empty($data))
            {
                $this->Session->setFlash(__('Invalid Link', true)); 
                $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true);
            }
            else
            {                                                                                    
                $this->Job->del($id);
                $this->Session->setFlash(__('Your Job has been deleted', true)); 
                $this->redirect(array('controller'=>'jobs', 'action'=>'my_jobs'),null, true);
            }
        }
        else
        { 
            $this->Session->setFlash(__('Please login first', true));
            $this->redirect(array('controller'=>'employers', 'action'=>'login'),null, true);        
        }
    }   
    
 // ga pake    
    function add() {
		if (!empty($this->data)) {
			$this->Job->create();
			if ($this->Job->save($this->data)) {
				$this->Session->setFlash(__('The Job has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Job could not be saved. Please, try again.', true));
			}
		}
		$fields = $this->Job->Field->find('list');
		$clipboards = $this->Job->Clipboard->find('list');
		$employers = $this->Job->Employer->find('list');
		$templates = $this->Job->Template->find('list');
		$cities = $this->Job->City->find('list');
		$academics = $this->Job->Academic->find('list');
		$this->set(compact('fields', 'clipboards', 'employers', 'templates', 'cities', 'academics'));
	} 

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Job.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('job', $this->Job->read(null, $id));
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this->Job->create();
			if ($this->Job->save($this->data)) {
				$this->Session->setFlash(__('The Job has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Job could not be saved. Please, try again.', true));
			}
		}
		$fields = $this->Job->Field->find('list');
		$clipboards = $this->Job->Clipboard->find('list');
		$employers = $this->Job->Employer->find('list');
		$templates = $this->Job->Template->find('list');
		$cities = $this->Job->City->find('list');
		$academics = $this->Job->Academic->find('list');
		$this->set(compact('fields', 'clipboards', 'employers', 'templates', 'cities', 'academics'));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Job', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Job->save($this->data)) {
				$this->Session->setFlash(__('The Job has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Job could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Job->read(null, $id);
		}
		$fields = $this->Job->Field->find('list');
		$clipboards = $this->Job->Clipboard->find('list');
		$employers = $this->Job->Employer->find('list');
		$templates = $this->Job->Template->find('list');
		$cities = $this->Job->City->find('list');
		$academics = $this->Job->Academic->find('list');
		$this->set(compact('fields','clipboards','employers','templates','cities','academics'));
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Job', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Job->del($id)) {
			$this->Session->setFlash(__('Job deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}
}
?>
